//
//  LXLChangePhoneViewController.m
//  FZAH
//
//  Created by 李小龙 on 17/4/17.
//  Copyright © 2017年 zdqk. All rights reserved.
//

#import "LXLChangePhoneViewController.h"

@interface LXLChangePhoneViewController ()<UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UIView *backView;
@property (weak, nonatomic) IBOutlet UITextField *phoneNumberTextField;
@property (weak, nonatomic) IBOutlet UITextField *verificationcodeTextField;
@property (weak, nonatomic) IBOutlet UIButton *verificationcodeButton;

@property (strong, nonatomic) NSTimer *myTimer;
@property (nonatomic, assign) NSInteger num;  // 验证码倒计时60秒

@end

@implementation LXLChangePhoneViewController
- (IBAction)verificationcodeButtonAction:(id)sender {
    [self.view endEditing:YES];
    
    if (![LXLIsPhoneNumber valiMobile:_phoneNumberTextField.text]) {
        [self showAlertMessage:@"请填写正确的手机号码"];
        return;
    }
    
    _verificationcodeButton.userInteractionEnabled = NO;
    
    NSDictionary *dic = @{@"mtel":_phoneNumberTextField.text};
    NSString *md5_mobile = [NSString stringWithFormat:@"%@%@", _phoneNumberTextField.text, BASE_SMS_Key];
    [dic setValue:[[md5_mobile md5] lowercaseString] forKey:@"sign"];
    [dic setValue:@"2" forKey:@"vctype"];
    
    [MYAFNetworking POST:URL_SMS parameters:dic success:^(NSURLSessionDataTask *task, id responseObject) {
        NSDictionary *dics = responseObject;
        
        if ([[dics objectForKey:@"code"] isEqualToString:@"200"]) {
            [MBProgressHUD myShowHUDAddedTo:self.view labelText:@"验证码发送成功!" animated:YES];
            
        }else{
            
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError *error) {
        
    }];
    
    self.myTimer =  [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    [self.verificationcodeButton setTitleColor:[UIColor grayTextColor] forState:UIControlStateNormal];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"修改手机号";
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonItemAction:)];
    NSDictionary *dic = [NSDictionary dictionaryWithObject:[UIColor ThemeColor] forKey:NSForegroundColorAttributeName];
    [rightItem setTitleTextAttributes:dic forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = rightItem;
    [self hiddenShadowImage:NO];
    
    [self.backView setShadowWith:nil opacity:0 offset:CGSizeMake(0, 4)];
    self.num = 60;
    
    [self.phoneNumberTextField becomeFirstResponder];
}

- (void)rightBarButtonItemAction:(id)sender {
    if (![LXLIsPhoneNumber valiMobile:_phoneNumberTextField.text]) {
        [self showAlertMessage:@"请填写正确的手机号码"];
        return;
    }
    if (!TextIsNotNil(_verificationcodeTextField.text)) {
        [self showAlertMessage:@"请填写验证码"];
        return;
    }
    
    NSDictionary *dic = @{@"mtel":_phoneNumberTextField.text,
                          @"verificationcode":_verificationcodeTextField.text};
    
    __weak typeof(self) weakSelf = self;
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    [MYAFNetworking POST:URL_Save_Mtel parameters:dic success:^(NSURLSessionDataTask *task, id responseObject) {
        NSDictionary *dics = responseObject;
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
        if ([[dics objectForKey:@"code"] isEqualToString:@"200"]) {
            [UserInfo shareInstance].user.mtel = weakSelf.phoneNumberTextField.text;
            [[UserInfo shareInstance] updateUserModel];
            
            [weakSelf disMissSelf];
        } else {
            [MBProgressHUD showError:weakSelf.view title:responseObject[@"message"] code:[dics objectForKey:@"code"] animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [MBProgressHUD showError:weakSelf.view title:@"" code:@"" animated:YES];
    }];
}

- (void)timerAction{
    [_verificationcodeButton setTitle:[NSString stringWithFormat:@"%lds",(long)_num--] forState:UIControlStateNormal];
    if (_num == 0) {
        [self stopTimer];
    }
}
- (void)stopTimer {
    [_verificationcodeButton setTitle:[NSString stringWithFormat:@"获取验证码"] forState:UIControlStateNormal];
    [_verificationcodeButton setTitleColor:[UIColor yellowTextColor] forState:UIControlStateNormal];
    _verificationcodeButton.userInteractionEnabled = YES;
    _num = 60;
    [_myTimer invalidate];
}

#pragma mark - textFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([string isEqualToString:@""]) {
        return YES;
    }
    
    if ([string isEqualToString:@" "]) {
        return NO;
    }
    
    if (textField.tag == 1000) {
        // 手机号
        if (textField.text.length >= 11) {
            return NO;
        }else{
            return YES;
        }
    }
    if (textField.tag == 1001) {
        // 验证码
        if (textField.text.length >= 4) {
            return NO;
        }else{
            return YES;
        }
    }
    return YES;
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [super touchesEnded:touches withEvent:event];
    [self.view endEditing:YES];
}

- (void)dealloc {
    [_myTimer invalidate];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
